﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Search.aspx.cs" company="Tobias Lekman">
//   Licensed under Microsoft Public License (Ms-PL). See lekman.codeplex.com/license for more information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace LekmanCom
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;

    using LekmanCom.net.bing.api;

    /// <summary>
    /// The search.
    /// </summary>
    public partial class Search : Page
    {
        #region Constants and Fields

        /// <summary>
        /// AppId for the Bing API.
        /// </summary>
        private const string AppId = "B232CFCC595D44C44EB878DCF606CC67118CAF5B";

        #endregion

        #region Methods

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.QueryText.Text = this.Page.Request.QueryString["q"];
            this.PerformSearch();
        }

        /// <summary>
        /// Builds the search request for Bing.
        /// </summary>
        /// <param name="query">
        /// The user query.
        /// </param>
        /// <returns>
        /// The composed Bing API web request.
        /// </returns>
        private static SearchRequest BuildRequest(string query)
        {
            return new SearchRequest
                {
                    AppId = AppId, 
                    Query = string.Format("(site:lekman.com AND {0})", query), 
                    Sources = new[] { SourceType.Web }, 
                    Version = "2.0", 
                    Market = "en-us", 
                    Adult = AdultOption.Moderate, 
                    AdultSpecified = true, 
                    Web = new WebRequest { Count = 15, CountSpecified = true }
                };
        }

        /// <summary>
        /// Removes the default pages and archive pages.
        /// </summary>
        /// <param name="response">
        /// The unfiltered search response.
        /// </param>
        /// <returns>
        /// The filtered results.
        /// </returns>
        private static IEnumerable<WebResult> RemoveDefaultAndArchive(SearchResponse response)
        {
            return
                response.Web.Results.Where(
                    r =>
                    !r.DisplayUrl.Contains("archive") & r.DisplayUrl != "blog.lekman.com" &
                    !r.DisplayUrl.StartsWith("blog.lekman.com/feeds") & !r.DisplayUrl.StartsWith("lekman.com"));
        }

        /// <summary>
        /// Performs the search and binds the results to the repeater.
        /// </summary>
        private void PerformSearch()
        {
            using (var service = new BingService())
            {
                SearchRequest request = BuildRequest(this.Page.Request.QueryString["q"] ?? "tobias");
                SearchResponse response = service.Search(request);

                if (response.Web.Results == null)
                {
                    this.NoResults.Visible = true;
                    return;
                }

                this.SearchResults.DataSource = RemoveDefaultAndArchive(response);
                this.SearchResults.DataBind();
            }
        }

        #endregion
    }
}